package com.yide.myworld.service.impl;

import com.yide.myworld.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Value;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;

/**
 * 星甫云短信平台
 * @author d
 * @date 2023/3/23 21:24
 */
@Slf4j
@Service
@RefreshScope
public class UserSmsSendService {


    /**
     * 产品sp_id
     */
    @Value("${xingfuyun.sms.spId:null}")
    private String spId;

    /**
     * 地址
     */
    @Value("${xingfuyun.sms.url:null}")
    private String url;

    /**
     * 短信模板
     */
    @Value("${xingfuyun.sms.smsTemplate:null}")
    private String smsTemplate;
    /**
     * 密码（和签名二选一即可）,通过sp_id的密码进行md5处理
     */
    @Value("${xingfuyun.sms.password:null}")
    private String password;

    private String common(String url, String mobile, String code,String type) {
        String json;
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        try {
            java.util.Map<String, String> paras = new java.util.HashMap<>();
            paras.put("sp_id", spId);
            paras.put("mobile", mobile);
            paras.put("content", smsTemplate.replace("%4%", code).replace("%18%", type));
            paras.put("password", password);
            //根据参数Key排序（顺序）
            java.util.TreeMap<String, String> sortParas = new java.util.TreeMap<>();
            sortParas.putAll(paras);
            //Java实现PHP中的http_build_query()效果
            String sortedQueryString = specialUrlEncode(http_build_query(sortParas));

            httpClient = HttpClients.createDefault();
            httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            //设置请求的参数
            StringEntity stringEntity = new StringEntity(sortedQueryString.toString(), "utf-8");
            stringEntity.setContentType("text/json");
            httpPost.setEntity(stringEntity);
            HttpResponse response = httpClient.execute(httpPost);
            json = EntityUtils.toString(response.getEntity(), "utf-8");
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApiException(e.getMessage());
        } finally {
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }



    /**
     * 发送短信
     * @return
     */
    public String smsSend(String mobile, String code,String type) {
        String smsUrl = url;
        //请求星甫云服务端
        return common(smsUrl,mobile,code,type);
    }


    /**
     * 特殊Url编码
     * @param value
     * @return
     */
    public static String specialUrlEncode(String value) {
        return value.replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
    }

    /**
     * Java实现PHP中的http_build_query()效果
     *
     * @param array key=value形式的二位数组
     * @return
     */
    public static String http_build_query(Map<String, String> array) {
        String reString = null;
        //遍历数组形成akey=avalue&bkey=bvalue&ckey=cvalue形式的的字符串
        Iterator it = array.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry) it.next();
            String key = entry.getKey();
            String value = entry.getValue();
            reString += key + "=" + value + "&";
        }
        reString = reString.substring(0, reString.length() - 1);
        //将得到的字符串进行处理得到目标格式的字符串
        try {
            reString = java.net.URLEncoder.encode(reString, "utf-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        reString = reString.replace("%3D", "=").replace("%26", "&");
        // 去除第一个多余的null符号
        return reString.substring(4);
    }


}
